package handlers

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"strconv"
	"take-out-mgr/cache"
	"take-out-mgr/model"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	content := c.PostForm("content")
	good := model.Good{
		Name:    name,
		Content: content,
	}
	redis_key := "add_" + name
	jsonData, _ := json.Marshal(good)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	model.DB.Create(&good)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": good,
	})
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var data []model.Good
	redis_key := "list_" + strconv.Itoa(page)
	cacheDat, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheDat == "" {
		model.DB.Offset(offset).Limit(size).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheDat), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})

}
func ListId(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var data model.Good
	redis_key := "listid_" + strconv.Itoa(id)
	cacheDat, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheDat == "" {
		model.DB.Where("id=?", id).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheDat), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
}
